using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Student.Models;

namespace Student.Controllers;

public class StudentController : Controller
{
    private readonly StudentDbContext _db;
    public StudentController()
    {
        _db=new StudentDbContext();
    }
    public IActionResult Index(string keyword)
    {   
        if(string.IsNullOrEmpty(keyword)){
            var list=_db.Students.ToList();
            return View(list);
        }
        var res=_db.Students.Where(x=>x.StudentName.Contains(keyword)).ToList();
        return View(res);
    }
    public IActionResult Edit(int id)
    {
        var obj=_db.Students.FirstOrDefault(x=>x.Id==id);
        return View (obj);
    }
    [HttpPost]
    public IActionResult Edit(Students input)
    {
        var obj=_db.Students.FirstOrDefault(x=>x.Id==input.Id);
        if(obj==null)
        {
            return NotFound();
        }
        obj.StudentName=input.StudentName;
        _db.Students.Update(obj);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    public IActionResult Delete(int id){
        var obj=_db.Students.FirstOrDefault(x=>x.Id==id);
        return View(obj);
    }
    public IActionResult DeleteConfirm(int id)
    {
        var obj= _db.Students.FirstOrDefault(x=>x.Id==id);
        if(obj==null){
            return NotFound();
        }
        _db.Students.Remove(obj);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
    public IActionResult Adds(){
        return View();
    }
    [HttpPost]
    public IActionResult Adds(Students input){
        _db.Students.Add(input);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }
}   